<?php
include 'mysql.inc.php';
$choices = [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1],[1,1,2],[1,1,3],[1,2,2],[1,3,3]];


session_start();
$userid = $_SESSION['user'];
if(!isset($userid)) exit;


query('BEGIN');
query('SET AUTOCOMIIT=0');

try {
	$sql = "select * from `user` where id='{$userid}' for update";
	$rs = query($sql);
	$user = mysql_fetch_assoc($rs);
	
	if (!$user){
		query('COMMIT');
		query('SET AUTOCOMMIT=1');
		closeConnection();
		exit;
	}
	if ($user['rank'] > 0) {
		
		$choice = $user['choice'];
		//echo $choice;
		if ($choice >0) {
			$choice = $choice - 1;
			
			$sql = "update `user` set `choice`='{$choice}' where id='{$userid}'";
			query($sql);
			$result = array("res" => 'success', "choice" => $choice, "datas" => $choices[rand(0, count($choices) - 1)], 'get' => '0');
		} else {
			$result = array("res" => 'nochoice', "choice" => 0, "datas" => $choices[rand(0, count($choices) - 1)], 'get' => '0');
		}
		
		echo json_encode($result);
	} else {
		if ($user['choice'] < 1) {
			$result = array("res" => 'nochoice', "choice" => 0, "datas" => $choices[rand(0, count($choices) - 1)], 'get' => '0');
			echo json_encode($result);
		} else {
			$sql = "update `user` set `choice`=`choice` - 1 where id='{$userid}'";
			query($sql);
			
			if(rand(0, 1000) < 950) {
				$result = array("res" => 'success', "choice" => $user['choice']-1, "datas" => $choices[rand(0, count($choices) - 1)], 'get' => '0');
				echo json_encode($result);
			} else {
				$rank = rand(1, 3);
				$sql = "SELECT * FROM `reward` WHERE `allow_date`= CURDATE() and `get`=0 and `rank`='{$rank}' LIMIT 0, 1 FOR UPDATE";
				$rs = query($sql);
				$row = mysql_fetch_assoc($rs);
				if ($row){
					$rewardid = $row['id'];
					$sql = "update `user` set `rank`='{$rank}' where id='{$userid}'";
					query($sql);
					$sql = "update `reward` set `get`=1 where id='{$rewardid}'";
					query($sql);
					$result = array("res" => 'success', "choice" => $user['choice']-1, "datas" =>  [$rank, $rank, $rank], 'get' => '1');
					echo json_encode($result);
				} else {
					$result = array("res" => 'success', "choice" => $user['choice']-1, "datas" => $choices[rand(0, count($choices) - 1)], 'get' => '0');
					echo json_encode($result);
				}
			}
		}
	}
	query('COMMIT');
} catch(Exception $e) {
	query('ROLLBACK');
	echo $e;
}
query('SET AUTOCOMMIT=1');
closeConnection();
?>